package com.kdtech.analyse.app;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.StringUtils;
import com.kdtech.analyse.AnalyseNews;

/**
 * @链接 http://m.guokr.com/
 * @名字 果壳精选APP
 * @作者 dhy
 */
public class GuokrAppAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://m.guokr.com/article/[0-9]+/",
		"http://m.guokr.com/post/[0-9]+/",
		"http://m.guokr.com/question/[0-9]+/",
	};


	
	public boolean isDetailPage(String url) {
		for (int i=0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return false;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		
		title =doc.select("div.content-th h1").text();
		if(StringUtils.isBlank(title))
		{
			title =doc.select("h1.title").text();
		}
		
		date=DateUtils.matchDate(doc.select("div.content-th-info").text());
		if(date==null){
			date=DateUtils.matchDate(doc.select("div.publish").text());
		}
		
		content =HtmlCleaner.getContentHtml(url, doc.select("div.document"));
		if(StringUtils.isBlank(content)){
			content =HtmlCleaner.getContentHtml(url, doc.select("div#postContent"));
		}
		if(StringUtils.isBlank(content)){
			content =HtmlCleaner.getContentHtml(url, doc.select("div#askContent"));
		}
		
		
		author = doc.select("div.content-th-info a").text();
		if(StringUtils.isBlank(author)){
			Elements authorList = doc.select("div.publish a");
			if(authorList.size() > 1){
				author = authorList.get(1).text();
			}
		}
		if(StringUtils.isBlank(author)){
			Elements authorList = doc.select("h6.author");
			if(authorList.size() > 0){
				author = authorList.get(0).text();
			}
		}
		
		news.setTitle(StringUtils.trimSpace(title));
		news.setAuthor(author);
		news.setContent(content);
		news.setDate(date);

		return news;

	}

	

	

	
}

